
package com.zdkj.subway.st.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdkj.common.security.service.PigxUser;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.common.security.util.SecurityUtils;
import com.zdkj.subway.st.dto.in.SwStAuditDTO;
import com.zdkj.subway.st.entity.SwStPlanDay;
import com.zdkj.subway.st.entity.SwStPlanWeek;
import com.zdkj.subway.st.mapper.SwStPlanWeekMapper;
import com.zdkj.subway.st.service.SwStPlanDayService;
import com.zdkj.subway.st.service.SwStPlanWeekService;
import com.zdkj.subway.st.util.JdbcUtil;
import com.zdkj.subway.st.util.SubwayStConstants;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


@Slf4j
@Service
@AllArgsConstructor
public class SwStPlanWeekServiceImpl extends ServiceImpl<SwStPlanWeekMapper, SwStPlanWeek> implements SwStPlanWeekService {


    private final SwStPlanWeekMapper swStPlanWeekMapper;

    private final SwStPlanDayService swStPlanDayService;
    @Override
    public boolean submitBatch(List<Integer> ids) {
        Collection<SwStPlanWeek> swStPlanWeeks = listByIds(ids);
        for (SwStPlanWeek swStPlanWeek : swStPlanWeeks) {
            if(SubwayStConstants.AUDIT_STATUS_NOT_SUBMIT.equals(swStPlanWeek.getCheckStatus())||
                    SubwayStConstants.AUDIT_STATUS_FAIL.equals(swStPlanWeek.getCheckStatus())){
                swStPlanWeek.setCheckSubmit(SubwayStConstants.SUBMIT_STATUS_PASS);
                swStPlanWeek.setCheckStatus(SubwayStConstants.AUDIT_STATUS_WAIT);
            }
        }
        return updateBatchById(swStPlanWeeks);
    }

    @Override
    public boolean auditBatch(SwStAuditDTO swStAuditDTO) {
        PigxUser user = SecurityUtils.getUser();
        Collection<SwStPlanWeek> swStPlanWeeks = listByIds(swStAuditDTO.getIds());
        String status = swStAuditDTO.getResult()? SubwayStConstants.AUDIT_STATUS_PASS
                : SubwayStConstants.AUDIT_STATUS_FAIL;
        for (SwStPlanWeek swStPlanWeek : swStPlanWeeks) {
            if(SubwayStConstants.AUDIT_STATUS_WAIT.equals(swStPlanWeek.getCheckStatus())){
                swStPlanWeek.setCheckStatus(status);
                swStPlanWeek.setCheckSuggest(swStAuditDTO.getSuggestions());
                swStPlanWeek.setCheckPersonId(user.getId());
                swStPlanWeek.setCheckTime(LocalDateTime.now());
            }
        }
        return updateBatchById(swStPlanWeeks);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean decompose(Long id, List<SwStPlanDay> planDays) {
        SwStPlanWeek swStPlanWeek = swStPlanWeekMapper.selectById(id);
        if("1".equals(swStPlanWeek.getIsDecompose())){
            // 如果是已分解不能再分解
            log.warn("Plan ({}) is decomposed state, cannot be decomposed any more.", id);
            return false;
        }
        int decomposeNumber = 0;
        Set<String> decomposedWeek = new HashSet<>();
        if(planDays.size()<=0 || planDays==null){
            return false;
        }
        //周分解到日 单号后要加01 以此类推
        int i = 1;
        String no = "";
        for (SwStPlanDay planday : planDays) {
            if(planday.getId() == null){
                // 如果是新增分解数据，设置默认值
                ObjectUtils.setDefaultFiledValueOfBelongToLine(planday);
                planday.setPlanWeekId(swStPlanWeek.getId());
                planday.setPlanType(swStPlanWeek.getPlanType());
                planday.setWorkTime(swStPlanWeek.getWorkTime());
                planday.setPlanMonth(swStPlanWeek.getPlanMonth());
                planday.setTicketType(swStPlanWeek.getTicketType());
                planday.setRemark(swStPlanWeek.getRemark());
                planday.setCheckStatus(SubwayStConstants.AUDIT_STATUS_NOT_SUBMIT);
                planday.setCheckSubmit(SubwayStConstants.SUBMIT_STATUS_WAIT);
                if(i<10){
                    no = "0"+i;
                }else {
                    no = ""+i;
                }
                planday.setNumbers(swStPlanWeek.getNumbers()+no);//单号
                planday.setOperator(swStPlanWeek.getOperator());
                i++;
            }
            decomposeNumber += planday.getTicketNumber();
            decomposedWeek.add(planday.getPlanWeek());
        }
        swStPlanWeek.setDecomposeNumber(decomposeNumber);
        // 已分解周，多个用逗号分隔
        swStPlanWeek.setDecomposeWeek(String.join(",", decomposedWeek));
        // 计划张数，如果现计划张数不为空则取现计划张数
        int planNumber = swStPlanWeek.getPlanNumberNow() != null ? swStPlanWeek.getPlanNumberNow() : swStPlanWeek.getPlanNumberOld();
        // 如果分解数等于计划数，将状态置为“已分解”
        if(decomposeNumber == planNumber){
            swStPlanWeek.setIsDecompose("1");
        }
        swStPlanWeekMapper.updateById(swStPlanWeek);
        // FIXME 未处理删除操作
        swStPlanDayService.saveOrUpdateBatch(planDays);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateDecompose(Long id, List<SwStPlanDay> planDays) {
        SwStPlanWeek swStPlanWeek = swStPlanWeekMapper.selectById(id);
        int decomposeNumber = 0;
        Set<String> decomposedWeek = new HashSet<>();
        if(planDays.size()<=0 || planDays==null){
            return false;
        }
        if(!"".equals(id.toString())){
            swStPlanDayService.delByPlanWeekId(id);
        }
        for (SwStPlanDay planday : planDays) {
            if(planday.getId() == null){
                // 如果是新增分解数据，设置默认值
                ObjectUtils.setDefaultFiledValueOfBelongToLine(planday);
                planday.setPlanWeekId(swStPlanWeek.getId());
                planday.setPlanType(swStPlanWeek.getPlanType());
                planday.setWorkTime(swStPlanWeek.getWorkTime());
                planday.setPlanMonth(swStPlanWeek.getPlanMonth());
                planday.setTicketType(swStPlanWeek.getTicketType());
                planday.setRemark(swStPlanWeek.getRemark());
                planday.setCheckStatus(SubwayStConstants.AUDIT_STATUS_NOT_SUBMIT);
                planday.setCheckSubmit(SubwayStConstants.SUBMIT_STATUS_WAIT);
            }
            decomposeNumber += planday.getTicketNumber();
            decomposedWeek.add(planday.getPlanWeek());
        }
        swStPlanWeek.setDecomposeNumber(decomposeNumber);
        // 已分解周，多个用逗号分隔
        swStPlanWeek.setDecomposeWeek(String.join(",", decomposedWeek));
        // 计划张数，如果现计划张数不为空则取现计划张数
        int planNumber = swStPlanWeek.getPlanNumberNow() != null ? swStPlanWeek.getPlanNumberNow() : swStPlanWeek.getPlanNumberOld();
        // 如果分解数等于计划数，将状态置为“已分解”
        if(decomposeNumber == planNumber){
            swStPlanWeek.setIsDecompose("1");
        }
        swStPlanWeekMapper.updateById(swStPlanWeek);
        // FIXME 未处理删除操作
        swStPlanDayService.saveOrUpdateBatch(planDays);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delByPlanMonthId(Long id) {
        try {
            JdbcUtil.exeSqlCrud("delete from sw_tk_public_plan_week where PLAN_MONTH_ID = " + id);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        return true;
    }
}
